package com.config.security;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Component;

import java.util.Collection;

/**
 * 权限控制 -> 判断用户角色
 */
@Slf4j
@Component
public class CustomerUrlDecisionManager implements AccessDecisionManager {

    @Override
    public void decide(Authentication authentication, Object o, Collection<ConfigAttribute> collection) throws AccessDeniedException, InsufficientAuthenticationException {
//        log.info("Collection, {}", collection);
        log.info("getAttribute, {}", JSON.toJSON(collection));
        for (ConfigAttribute configAttribute : collection) {
            //当前url所需要的一个角色
            String needRole = configAttribute.getAttribute();
//            System.out.println("needRole: " + needRole);
            //判断角色是否登录即可访问的角色, 此角色在CustomerFilter中设置
            if ("ROLE_LOGIN".equals(needRole)) {
                if (authentication instanceof AnonymousAuthenticationToken) {
                    throw  new AccessDeniedException("尚未登录, 请登录!!!");
                }
                return;
            }
            //这里相当于直接从user实体类中继承的getAuthorities中获取权限组。
            // 在登录的时候会走securityConfig类中重写的UserDetailsService接口中的loadUserByUserName, 并将权限设置到security全局中去。
            Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
            System.out.println("开始校验权限，"+JSON.toJSONString(authorities));
            for (GrantedAuthority authority : authorities) {
                if (authority.getAuthority().equals(needRole)) {
                    System.out.println("这是什么？" + needRole);
                    return;
                }
            }
        }
        //这里放在外面 需要注意
        throw new AccessDeniedException("权限不足, 请联系管理员!");
    }

    @Override
    public boolean supports(ConfigAttribute configAttribute) {
        return false;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return false;
    }
}
